package bean;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import java.sql.Connection;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.faces.context.FacesContext;

import javax.naming.Context;
import javax.naming.InitialContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.type.WhenNoDataTypeEnum;
import net.sf.jasperreports.engine.util.JRLoader;


import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;

import oracle.binding.BindingContainer;

public class HacerReporte {
    public HacerReporte() {
    }

    public String btoVerReport_action() {

        DCIteratorBinding idPersona =
            (DCIteratorBinding)getBindings().get("personaVO1Iterator");
        String personaId =
            idPersona.getCurrentRow().getAttribute("Idpersona").toString();
        System.out.println("IdPersona " + personaId);
        Map m = new HashMap();
        String descripcionMas = "Mundo";
        String descripcionMenos = "Mundo";
        String descripcionDif = "Mundo";

        m.put("Idpersona",
              personaId); // donde se le envia el parametro del id pserona al jasper

        m.put("descripcionMas", descripcionMas); //Colocar la Descripcion Mas
        m.put("descripcionMenos",
              descripcionMenos); //Colocar la Descripcion Menos
        m.put("descripcionDif", descripcionDif); //Colocar la Descripcion Dif


        try {
            runReport("reportResultado2.jasper", m);
            //runReport2();
        } catch (Exception e) {
        }
        return null;
    }

    public void runReport2() {
        Map m = new HashMap();
        String parametro = "Mundo";
        m.put("prueba1", parametro);

        LinkedList<String> listaEmpleados = new LinkedList<String>();
        listaEmpleados.add("Hola");
        listaEmpleados.add("Holaf");
        listaEmpleados.add("hola2");
        try {
            ServletContext context = getContext();
            InputStream fs =
                context.getResourceAsStream("/report/prueba1.jasper");

            JasperReport reporte = (JasperReport)JRLoader.loadObject(fs);
            //JasperReport reporte = (JasperReport) JRLoader.loadObject("/report/prueba1.jasper");
            JasperPrint jasperPrint =
                JasperFillManager.fillReport(reporte, m, new JRBeanCollectionDataSource(listaEmpleados));
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT,
                                  jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE,
                                  new java.io.File("reporteEnPdf.pdf"));
            exporter.exportReport();
        } catch (JRException e) {
            e.printStackTrace();
        }
    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public Connection getDataSourceConnection(String dataSourceName) throws Exception {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup(dataSourceName);
        return ds.getConnection();
    }

    private Connection getConnection() throws Exception {
        return getDataSourceConnection("DS"); // datasource name should be defined in weblogic
    }

    public ServletContext getContext() {
        return (ServletContext)getFacesContext().getExternalContext().getContext();
    }

    public HttpServletResponse getResponse() {
        return (HttpServletResponse)getFacesContext().getExternalContext().getResponse();
    }

    public static FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    public void runReport(String repPath,
                          java.util.Map param) throws Exception {
        Connection conn = null;
        try {
            HttpServletResponse response = getResponse();
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentType("application/pdf");
            ServletContext context = getContext();
            InputStream fs = context.getResourceAsStream("/report/" + repPath);

            JasperReport template = (JasperReport)JRLoader.loadObject(fs);
            template.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);

            conn = getConnection();
            //conn = (Connection)new JRBeanCollectionDataSource(listaEmpleados);
            //JasperPrint print = JasperFillManager.fillReport(template, param, conn);
            JasperPrint print =
                JasperFillManager.fillReport(template, param, conn);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JasperExportManager.exportReportToPdfStream(print, baos);
            out.write(baos.toByteArray());
            out.flush();
            out.close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (Exception jex) {
            jex.printStackTrace();
        } finally {
            close(conn);
        }
    }

    public void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}
